import Taro, {
    canIUse,
    getDeviceInfo as getDeviceInfoData,
    getWindowInfo as getWinInfo,
    getSystemInfoSync as systemInfoSync,
    getAppBaseInfo as appBaseInfo
} from '@tarojs/taro';
import { isFunction } from '../core/type';
import { hasProperty } from '../core/object';

interface IDeviceInfo extends Omit<Taro.getDeviceInfo.Result, 'deviceAbi' | 'CPUType'> {}
/**
 * 获取设备基础信息，兼容新旧 API
 * @returns {IDeviceInfo} 设备基础信息
 *
 */

export const isCanUse = function (name: string, api?: any) {
    if (isFunction(canIUse) && hasProperty(Taro, 'canIUse')) {
        return canIUse(name);
    }
    return isFunction(api) && hasProperty(Taro, name);
};
interface IDeviceInfo extends Omit<Taro.getDeviceInfo.Result, 'deviceAbi' | 'CPUType'> {}

export const getDeviceInfo = (): IDeviceInfo => {
    return isCanUse('getDeviceInfo', getDeviceInfoData) ? getDeviceInfoData() : systemInfoSync();
};

/**
 * 获取窗口信息，兼容新旧 API
 * @returns {Taro.getWindowInfo.Result} 窗口信息
 */
export const getWindowInfo = (): Taro.getWindowInfo.Result => {
    return isCanUse('getWindowInfo', getWinInfo) ? getWinInfo() : systemInfoSync();
};
/**
 * 获取应用基础信息，兼容新旧 API
 * @returns {Taro.getAppBaseInfo.Result} 应用基础信息
 */
export const getAppBaseInfo = (): Taro.getAppBaseInfo.Result => {
    return isCanUse('getAppBaseInfo', appBaseInfo) ? appBaseInfo() : systemInfoSync();
};
export const toPX = (value: number) => {
    const clientWidth = systemInfoSync().windowWidth;
    return (value * clientWidth) / 750;
};
